package nbpMaven2.nbpMaven2;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class NextCurrClass {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}
	
	public static BigDecimal getCurrencyValue(Date date, String scut) throws Exception{
		BigDecimal info = null;
		try{
			Calendar cal = Calendar.getInstance();
			cal.setTime(date);
			String year = (Integer.toString(cal.get(Calendar.YEAR))).substring(2, 4);
			String month = (Integer.toString(cal.get(Calendar.MONTH))).length() == 1 ? "0"+(Integer.toString(cal.get(Calendar.MONTH))) : (Integer.toString(cal.get(Calendar.MONTH)));
			String day = (Integer.toString(cal.get(Calendar.DAY_OF_MONTH))).length() == 1 ? "0"+(Integer.toString(cal.get(Calendar.DAY_OF_MONTH))) : (Integer.toString(cal.get(Calendar.DAY_OF_MONTH)));
			String recivedDate = year+month+day;
			
			URL link = new URL("http://www.nbp.pl/kursy/xml/dir.txt");
			BufferedReader in = null;
			URLConnection conn = null;
			conn = link.openConnection();
			conn.connect();
			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String inputline ="";
			boolean find = false;
			String nazwa = null;
			while ((inputline = in.readLine()) != null) {
				if(inputline.length() > 0 && inputline.charAt(0) == 'a'){
					Pattern patern = Pattern.compile(recivedDate);
					Matcher matchdata = patern.matcher(inputline);
					find = matchdata.find();
					if (find) {
						nazwa = "/kursy/xml/"+inputline+".xml";
						break;
					}
				}
			}
			if(find) info = getFinalValue(nazwa, scut.toUpperCase());
			else throw new Exception("Brak kurs�w z tego dnia!");	
		}
		
		catch(Exception ex){
			System.out.println(ex);
		}
		return info;
	}
	
	public static BigDecimal getFinalValue(String nameOfCurr, String scOfCurr) throws Exception{
        BigDecimal dibsVal = null;
		try{
			URL url = new URL("http://www.nbp.pl"+nameOfCurr);
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(url.openStream());
            String dibsCode = "";
            int cnt = 0;
            NodeList nLista = doc.getElementsByTagName("pozycja");
        	DecimalFormatSymbols symbols = new DecimalFormatSymbols();
        	symbols.setDecimalSeparator(',');
        	String patt = "0.#";
        	DecimalFormat df = new DecimalFormat(patt, symbols);
        	df.setParseBigDecimal(true);
            
            for(int i=0; i<nLista.getLength(); i++){
                Node nNode = nLista.item(i);
                if(nNode.getNodeType() == Node.ELEMENT_NODE){
                    Element elem = (Element)nNode; 
                    dibsCode = elem.getElementsByTagName("kod_waluty").item(0).getTextContent();
                    //System.out.println(dibsCode +" "+scOfCurr);
                    if(dibsCode.equals(scOfCurr)){
                    	dibsVal = (BigDecimal) df.parse((elem.getElementsByTagName("kurs_sredni").item(0).getTextContent()));
                    	System.out.print(dibsVal);
                    	cnt++;
                    	break;
                    }
                }
            }
            if (cnt == 0) throw new Exception("Nie ma takiej waluty!");
		}
		
		catch(Exception ex){
			System.out.println(ex);
		}
		return dibsVal;
	}

}
